package org.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.dao.IUserDao;
import org.entity.User;
import org.entity.UserData;
import org.util.SqlUtil;

public class UserDaoImpl implements IUserDao{
	public boolean queryUser(String username){
		boolean flag=false;
		SqlUtil su=new SqlUtil();
		String sql="select count(1) from usertable where username='"+username+"'";
		ResultSet rs = su.queryUtil(sql);
		try {
			if(rs.next()){
				if(rs.getInt(1)>0){
					flag=true;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flag;
	}
	public boolean queryPassword(User user){
		boolean flag=false;
		SqlUtil su=new SqlUtil();
		String sql="select password from usertable where username='"+user.getUsername()+"'";
		ResultSet rs = su.queryUtil(sql);
		try {
				if(rs.next()){
					if(rs.getString(1).equals(user.getPassword())){
						flag=true;
					}
				}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flag;
	}
	public int addUser(User user){
		SqlUtil su=new SqlUtil();
		String sql="insert into usertable values('"+user.getUsername()+"','"+user.getPassword()+"')";
		int i = su.updateUtil(sql);
		return i;
	}
	
	public UserData queryUserData(String username) {
		UserData ud=new UserData();
		SqlUtil su=new SqlUtil();
		String sql="select * from userdata where username='"+username+"'";
		ResultSet rs = su.queryUtil(sql);
		try {
			if(rs.next()){
				ud.setUsername(rs.getString("username"));
				ud.setName(rs.getString("name"));
				ud.setSchool(rs.getString("school"));
				ud.setAddress(rs.getString("address"));
				ud.setBeizhu("beizhu");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ud;
	}
	public int addUserData(UserData userData) {
		SqlUtil su=new SqlUtil();
		String sql="insert into userdata values('"+userData.getUsername()+"','"+userData.getName()+"','"+userData.getSchool()+"','"+userData.getAddress()+"','"+userData.getBeizhu()+"')";
		int i = su.updateUtil(sql);
		return i;
	}
	@Override
	public int alterUserData(UserData userData) {
		SqlUtil su=new SqlUtil();
		String sql="update userdata set name='"+userData.getName()+"',school='"+userData.getSchool()+"',address='"+userData.getAddress()+"',beizhu='"+userData.getBeizhu()+"' where username='"+userData.getUsername()+"'";
		int i = su.updateUtil(sql);
		return i;
	}
	@Override
	public boolean queryUserExits(UserData userData) {
		SqlUtil su=new SqlUtil();
		String sql="select count(1) from userdata where username='"+userData.getUsername()+"'";
		ResultSet rs = su.queryUtil(sql);
		try {
			if(rs.next()){
				if(Integer.parseInt(rs.getString(1))>0){
					return true;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
}